﻿using Common;
using DBUtility;
using Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BaseDal
{
    public class PostDal
    {
        private static readonly Lazy<PostDal> dal = new Lazy<PostDal>(() => new PostDal());
        public static PostDal Instance { get; } = dal.Value;

        private PostDal()
        { }

        private const string tableName = "Post";

        /// <summary>
        /// 查询数据是否存在
        /// </summary>
        /// <param name="strWhere"></param>
        /// <returns></returns>
        public bool IsExist(string strWhere)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select count(1) from " + tableName);
            strSql.Append(" where IsDelete=0 " + strWhere);
            return SqlHelper.Exists(strSql.ToString());
        }

        /// <summary>
        /// 查询SQL语句
        /// </summary>
        /// <param name="strWhere"></param>
        /// <returns></returns>
        public StringBuilder GetSelectSql(string strWhere = "")
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("SELECT ID,PostName,PostCode,SortCode,Notes,CreateTime,CreateUser,Status ");
            sb.Append("FROM " + tableName);
            sb.Append(" Where IsDelete=0 ");

            if (!string.IsNullOrEmpty(strWhere))
            {
                sb.Append(strWhere);
            }

            return sb;
        }

        /// <summary>
        /// 查询分页数据
        /// </summary>
        /// <param name="strWhere"></param>
        /// <returns></returns>
        public DataTable GetPageList(int pageSize, int pageIndex, string strWhere, string filedOrder, out int recordCount)
        {
            StringBuilder sb = GetSelectSql(strWhere);
            string countSql = PageHelper.CreateCountingSql(sb.ToString());
            recordCount = Convert.ToInt32(SqlHelper.GetSingle(countSql));
            string pageSql = PageHelper.CreatePageSql(recordCount, pageSize, pageIndex, sb.ToString(), filedOrder);
            DataSet ds = SqlHelper.Query(pageSql);
            return ds.Tables[0];
        }

        /// <summary>
        /// 查询数据
        /// </summary>
        /// <param name="strWhere"></param>
        /// <returns></returns>
        public List<Post> GetList(string strWhere)
        {
            StringBuilder sb = GetSelectSql(strWhere);
            DataSet ds = SqlHelper.Query(sb.ToString());
            return CommonOperation.ConvertDataTableToModelList<Post>(ds.Tables[0]);
        }

        /// <summary>
        /// 根据id查询实体类
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Post GetModelById(int id)
        {
            StringBuilder sb = GetSelectSql("and ID=@id");
            SqlParameter[] parameters =
            {
                new SqlParameter("@id",id)
            };
            DataSet ds = SqlHelper.Query(sb.ToString(), parameters);
            if (ds.Tables[0].Rows.Count > 0)
            {
                return CommonOperation.DataTableToModel<Post>(ds.Tables[0]);
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 新增岗位
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int AddPost(Post model)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("INSERT INTO " + tableName + "(");
            sb.Append("PostName,PostCode,SortCode,Notes,CreateTime,");
            sb.Append("CreateUser,Status)");
            sb.Append(" VALUES(");
            sb.Append("@postName,@postCode,@sortCode,@notes,");
            sb.Append("@createTime,@createUser,@status)");
            SqlParameter[] parameters =
           {
                new SqlParameter("@postName",model.PostName),
                new SqlParameter("@postCode",model.PostCode),
                new SqlParameter("@sortCode",model.SortCode),
                new SqlParameter("@notes",model.Notes),
                new SqlParameter("@createTime",model.CreateTime),
                new SqlParameter("@createUser",model.CreateUser),
                new SqlParameter("@status",model.Status)
            };
            int res = SqlHelper.ExecuteSql(sb.ToString(), parameters);
            return res;
        }

        /// <summary>
        /// 修改岗位
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int UpdatePost(Post model)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("Update " + tableName + " SET ");
            sb.Append("PostName=@postName,");
            sb.Append("PostCode=@postCode,");
            sb.Append("SortCode=@sortCode,");
            sb.Append("Notes=@notes,");
            sb.Append("UpdateTime=@updateTime,");
            sb.Append("UpdateUser=@updateUser ");
            sb.Append("WHERE ID=@id");
            SqlParameter[] parameters = {
                new SqlParameter("@postName",model.PostName),
                new SqlParameter("@postCode",model.PostCode),
                new SqlParameter("@sortCode",model.SortCode),
                new SqlParameter("@notes",model.Notes),
                new SqlParameter("@updateTime",model.UpdateTime),
                new SqlParameter("@updateUser",model.UpdateUser),
                new SqlParameter("@id",model.ID),
            };
            int result = SqlHelper.ExecuteSql(sb.ToString(), parameters);
            return result;
        }

        /// <summary>
        /// 删除岗位
        /// </summary>
        /// <param name="ids"></param>
        /// <param name="userName"></param>
        /// <returns></returns>
        public int DeletePost(List<string> ids, string userName)
        {
            StringBuilder strSql;
            List<CommandInfo> sqlList = new List<CommandInfo>();
            CommandInfo cmd;
            foreach (string id in ids)
            {
                strSql = new StringBuilder();
                strSql.Append(" update " + tableName + " set ");
                strSql.Append(" IsDelete=1,DeleteTime=GetDate(),DeleteUser='" + userName + "' ");
                strSql.Append(" Where ID=" + id);
                cmd = new CommandInfo(strSql.ToString());
                sqlList.Add(cmd);
            }
            int result = SqlHelper.ExecuteSqlTran(sqlList);
            return result;
        }

        /// <summary>
        /// 修改状态（启用、禁用）
        /// </summary>
        /// <param name="id"></param>
        /// <param name="userName"></param>
        /// <returns></returns>
        public int UpdateStatus(int id, int status, string userName)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("Update " + tableName + " SET ");
            sb.Append("Status=@status,");
            sb.Append("UpdateTime=GetDate(),");
            sb.Append("UpdateUser=@updateUser ");
            sb.Append("WHERE ID=@id");
            SqlParameter[] parameters = {
                new SqlParameter("@status",status),
                new SqlParameter("@updateUser",userName),
                new SqlParameter("@id",id),
            };
            int result = SqlHelper.ExecuteSql(sb.ToString(), parameters);
            return result;
        }
    }
}